package com.xyp.mesadmin.aspect;

import com.xyp.mesadmin.annotation.MyLog;
import com.xyp.mesadmin.log.service.LogService;
import com.xyp.mescommon.entity.log.Log;
import com.xyp.mescommon.entity.sys.SysUser;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * --- 加油，努力 ---
 *
 * @Author XYP
 * @Date 2024/9/29
 * @Solgne 从想做到能做
 * @Desc
 */
@Component
@Aspect
public class MyLogAspect {

    @Autowired
    private LogService logService;

    @Before("@annotation(com.xyp.mesadmin.annotation.MyLog)")
    public void log (JoinPoint joinPoint) {
        //1.获取当前时间
        Date date = new Date();

        //2.获取访问的远程ip
        ServletRequestAttributes request = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest req = request.getRequest();
        String ip = req.getRemoteAddr();

        //3.访问的账号用户名
        SysUser sysUser = (SysUser) WebUtils.getSessionAttribute(req, "userInfo");
        String name = "未登录";
        if (sysUser != null) {
            name = sysUser.getUsername();
        }

        //4.获取log字段
        String desc = getAnnotationDesc(joinPoint);

        Log log = new Log();
        log.setLogTime(date);
        System.out.println(date);
        log.setIp(ip);
        log.setName(name);
        log.setLog(desc);
        //插入数据库
        logService.addLog(log);

    }

    public static String getAnnotationDesc(JoinPoint joinPoint) {
        String value = "";
        String name = joinPoint.getSignature().getName();

        Method[] methods = joinPoint.getTarget().getClass().getDeclaredMethods();
        for (Method method : methods) {
            if (method.getName().equals(name)) {
                Annotation[] annotations = method.getDeclaredAnnotations();
                for (Annotation annotation : annotations) {
                    if (annotation.annotationType().equals(com.xyp.mesadmin.annotation.MyLog.class)) {
                        value = method.getAnnotation(MyLog.class).value();
                        return value;
                    }
                }
            }
        }
        return value;
    }
}
